<?php
/**
 * Created by PhpStorm.
 * User: gqn
 * Date: 2016/5/3
 * Time: 14:15
 */

namespace Admin\Controller;

class OrderController extends CommonController{

    const pagecount = 10;//每页显示数


    /**
     * 维修订单
     */
    public function Index(){
        $this->breadcrumb1='订单管理';
        $this->breadcrumb2='维修订单';

        $start_time = I('get.start_time');
        $end_time = I('get.end_time');
        $order_id = trim(I('get.order_id'));
        $user_name = trim(I('get.user_name'));
        $user_phone = trim(I('get.user_phone'));
        $master_name = trim(I('get.master_name'));
        $master_phone = trim(I('get.master_phone'));
        $order_status = I('get.order_status');


        if($start_time){
            $start_time = strtotime($start_time);
        }
        if($end_time){
            $end_time = strtotime($end_time);
        }
        if($start_time && $end_time) {
            $map['rep.set_time'] = array('between',$start_time.','.$end_time);
        }elseif($start_time){
            $map['rep.set_time'] = array('egt',$start_time);
        }
        if($order_id){
            $map['rep.repair_order_num_alias'] = array('like',"%$order_id%");
        }
        if($user_name){
            $map['usr.user_name'] = array('like',"%$user_name%");
        }
        if($user_phone){
            $map['usr.phone'] = array('like',"%$user_phone%");
        }
        if($master_name){
            $map['inf.id_name'] = array('like',"%$master_name%");
        }
        if($master_phone){
            $map['wok.phone'] = array('like',"%$master_phone%");
        }
        if($order_status !=0){
            $map['rep.status'] = array('eq',$order_status);
        }


        $count = M()->table('zsf_repair_order rep')
                ->field('rep.repair_order_num_alias,rep.set_time,rep.category_name,rep.doorplate,rep.worker_user_id,rep.fault_id_list,rep.mode_charging,rep.status,rep.shipping_addr,usr.user_name,usr.phone as user_phone,inf.id_name as master_name,inf.id_num as master_num,conf.name,wok.phone as master_phone')
                ->join("LEFT JOIN zsf_user usr on rep.user_id = usr.user_id")
                ->join("LEFT JOIN zsf_user_real_info inf on rep.worker_user_id = inf.user_id")
                ->join("LEFT JOIN zsf_config_status conf on rep.status = conf.status and user_type=1")
                ->join("LEFT JOIN zsf_user wok on inf.user_id = wok.user_id")
                ->where($map)
                ->order('rep.repair_order_id desc')
                ->count();

        $Page  = new \Think\Page($count,self::pagecount);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show  = $Page->show();// 分页显示输出

        $data = M()->table('zsf_repair_order rep')
                ->field('rep.repair_order_id,rep.book_time,rep.repair_order_num_alias,rep.doorplate,rep.set_time,rep.category_name,rep.worker_user_id,rep.fault_id_list,rep.mode_charging,rep.status,rep.shipping_addr,usr.user_name,usr.phone as user_phone,inf.id_name as master_name,inf.id_num as master_num,conf.name,wok.phone as master_phone')
                ->join("LEFT JOIN zsf_user usr on rep.user_id = usr.user_id")
                ->join("LEFT JOIN zsf_user_real_info inf on rep.worker_user_id = inf.user_id")
                ->join("LEFT JOIN zsf_config_status conf on rep.status = conf.status and user_type=1")
                ->join("LEFT JOIN zsf_user wok on inf.user_id = wok.user_id")
                ->where($map)
                ->limit($Page->firstRow.','.$Page->listRows)
                ->order('rep.repair_order_id desc')
                ->select();

        foreach($data as $k=>$v){
            $data[$k]['set_time'] = date('Y-m-d H:i:s',$data[$k]['set_time']);
            $data[$k]['book_time'] = date('Y-m-d H:i:s',$data[$k]['book_time']);
            if($data[$k]['mode_charging']=='1'){
                $data[$k]['mode_charging']='顺风';
            }elseif($data[$k]['mode_charging']=='2'){
                $data[$k]['mode_charging']='标准';
            }elseif($data[$k]['mode_charging']=='3'){
                $data[$k]['mode_charging']='专修';
            }
            if($data[$k]['worker_user_id']=='0'){
                $data[$k]['type'] = '0';
            }else{
                $data[$k]['type'] = '1';
            }
            $maps['fault_id'] = array('in',$data[$k]['fault_id_list']);
            $info = M('fault')->field('name')->where($maps)->select();
            $names = array_column($info,'name');
            $data[$k]['fault_name'] = implode(';',$names);

        }
        //分类
        $category = M("ConfigStatus")->field('id,name,status')->where("user_type = 1")->order("id asc")->select();
        $this->assign('status',$category);
        $this->assign('page',$show);
        $this->assign('repair',$data);
        $this->display('index');
    }


    /**
     * 待支付维修订单
     */
    public function Payment(){
        $this->breadcrumb1='订单管理';
        $this->breadcrumb2='待支付维修订单';

        $start_time = I('get.start_time');
        $end_time = I('get.end_time');
        $name = trim(I('get.name'));
        $phone = trim(I('get.phone'));
        if($start_time){
           $start_time = strtotime($start_time);
        }
        if($end_time){
           $end_time = strtotime($end_time);
        }
        if($name){
           $map['usr.user_name'] = array('like',"%$name%");
        }
        if($phone){
           $map['usr.phone'] = array('like',"%$phone%");
        }
        if($start_time && $end_time) {
           $map['rep.set_time'] = array('between',$start_time.','.$end_time);
        }elseif($start_time){
           $map['rep.set_time'] = array('egt',$start_time);
        }
        $map['rep.status'] = array('eq',7);


        $count = M()->table('zsf_repair_order rep')
            ->field('rep.repair_order_num_alias,rep.set_time,rep.doorplate,rep.fault_money,rep.diagnosis_cost,rep.tip,rep.total,usr.user_name,usr.phone,vol.total as volume_price')
            ->join('LEFT JOIN zsf_user usr on rep.user_id = usr.user_id')
            ->join('LEFT JOIN zsf_volume_list vol on rep.user_id = vol.user_id and vol.volume_id = rep.volume_list_id')
            ->where($map)
            ->count();

        $Page  = new \Think\Page($count,self::pagecount);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show  = $Page->show();// 分页显示输出

        $data = M()->table('zsf_repair_order rep')
                ->field('rep.repair_order_num_alias,rep.worker_user_id,rep.doorplate,rep.set_time,rep.fault_money,rep.diagnosis_cost,rep.tip,rep.total,usr.user_name,usr.phone,vol.total as volume_price')
                ->join('LEFT JOIN zsf_user usr on rep.user_id = usr.user_id')
                ->join('LEFT JOIN zsf_volume_list vol on rep.user_id = vol.user_id and vol.volume_id = rep.volume_list_id')
                ->where($map)->order('rep.set_time asc')
                ->limit($Page->firstRow.','.$Page->listRows)
                ->select();
        foreach($data as $k=>$v){
            $data[$k]['set_time'] = date('Y-m-d H:i:s',$data[$k]['set_time']);
        }
        $this->assign('page',$show);
        $this->assign('payment',$data);
        $this->display();
    }

    /**
     * 等待退款订单
     */

    public function Refund(){
        $this->breadcrumb1='订单管理';
        $this->breadcrumb2='待退款维修订单';

        $start_time = I('get.start_time');
        $end_time = I('get.end_time');
        $order_id = trim(I('get.order_id'));
        $user_name = trim(I('get.user_name'));
        $user_phone = trim(I('get.user_phone'));
        $master_name = trim(I('get.master_name'));
        $master_phone = trim(I('get.master_phone'));

        if($start_time){
            $start_time = strtotime($start_time);
        }
        if($end_time){
            $end_time = strtotime($end_time);
        }
        if($start_time && $end_time) {
            $map['rep.set_time'] = array('between',$start_time.','.$end_time);
        }elseif($start_time){
            $map['rep.set_time'] = array('egt',$start_time);
        }
        if($order_id){
            $map['rep.repair_order_num_alias'] = array('like',"%$order_id%");
        }
        if($user_name){
            $map['usr.user_name'] = array('like',"%$user_name%");
        }
        if($user_phone){
            $map['usr.phone'] = array('like',"%$user_phone%");
        }
        if($master_name){
            $map['inf.id_name'] = array('like',"%$master_name%");
        }
        if($master_phone){
            $map['wok.phone'] = array('like',"%$master_phone%");
        }
        //等待客服退款
        $map['rep.status'] = array('eq',12);

        $count = M()->table('zsf_repair_order rep')
            ->field('rep.repair_order_num_alias,rep.set_time,rep.category_name,rep.doorplate,rep.worker_user_id,rep.fault_id_list,rep.mode_charging,rep.status,rep.shipping_addr,usr.user_name,usr.phone as user_phone,inf.id_name as master_name,inf.id_num as master_num,conf.name,wok.phone as master_phone')
            ->join("LEFT JOIN zsf_user usr on rep.user_id = usr.user_id")
            ->join("LEFT JOIN zsf_user_real_info inf on rep.worker_user_id = inf.user_id")
            ->join("LEFT JOIN zsf_config_status conf on rep.status = conf.status and user_type=1")
            ->join("LEFT JOIN zsf_user wok on inf.user_id = wok.user_id")
            ->where($map)
            ->order('rep.repair_order_id desc')
            ->count();

        $Page  = new \Think\Page($count,self::pagecount);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show  = $Page->show();// 分页显示输出

        $data = M()->table('zsf_repair_order rep')
            ->field('rep.repair_order_id,rep.book_time,rep.repair_order_num_alias,rep.doorplate,rep.worker_user_id,rep.set_time,rep.category_name,rep.worker_user_id,rep.fault_id_list,rep.mode_charging,rep.status,rep.shipping_addr,usr.user_name,usr.phone as user_phone,inf.id_name as master_name,inf.id_num as master_num,conf.name,wok.phone as master_phone')
            ->join("LEFT JOIN zsf_user usr on rep.user_id = usr.user_id")
            ->join("LEFT JOIN zsf_user_real_info inf on rep.worker_user_id = inf.user_id")
            ->join("LEFT JOIN zsf_config_status conf on rep.status = conf.status and user_type=1")
            ->join("LEFT JOIN zsf_user wok on inf.user_id = wok.user_id")
            ->where($map)
            ->limit($Page->firstRow.','.$Page->listRows)
            ->order('rep.repair_order_id desc')
            ->select();

        foreach($data as $k=>$v){
            $data[$k]['set_time'] = date('Y-m-d H:i:s',$data[$k]['set_time']);
            $data[$k]['book_time'] = date('Y-m-d H:i:s',$data[$k]['book_time']);
            if($data[$k]['mode_charging']=='1'){
                $data[$k]['mode_charging']='顺风';
            }elseif($data[$k]['mode_charging']=='2'){
                $data[$k]['mode_charging']='标准';
            }elseif($data[$k]['mode_charging']=='3'){
                $data[$k]['mode_charging']='专修';
            }
            if($data[$k]['worker_user_id']=='0'){
                $data[$k]['type'] = '0';
            }else{
                $data[$k]['type'] = '1';
            }
            $maps['fault_id'] = array('in',$data[$k]['fault_id_list']);
            $info = M('fault')->field('name')->where($maps)->select();
            $names = array_column($info,'name');
            $data[$k]['fault_name'] = implode(';',$names);

        }
        $this->assign('page',$show);
        $this->assign('refund',$data);
        $this->display();
    }


    /**
     * 订单详情
     */
    public function Normal(){
        $this->breadcrumb1='订单管理';
        $this->breadcrumb2='维修订单';
        $this->breadcrumb3='订单详情';

        $this->url2=U('Order/index');
        $data = array();
        $order_id = I('get.order_id');
        $orderData = M()->DISTINCT(true)->table('zsf_repair_order rep')->field('rep.volume_list_id,rep.amount_paid,rep.is_refund,rep.repair_order_num_alias,rep.status,rep.set_time,rep.book_time,rep.category_name,rep.doorplate,rep.shipping_tel,rep.shipping_name,rep.shipping_addr,rep.total,rep.fixed_price,volume.total as price,rep.worker_tel,rep.protocol_id,inf.id_name as master_name,inf.user_id as worker_user_id,pro.maintain,pro.bond,pro.count,pro.unit')
                ->join("LEFT JOIN zsf_volume_list volume on rep.volume_list_id = volume.volume_list_id and volume.user_id = rep.user_id and volume.status =2")
                ->join("LEFT JOIN zsf_user_real_info inf on inf.user_id = rep.worker_user_id")
                ->join("LEFT JOIN zsf_repair_order_protocol pro on pro.protocol_id = rep.protocol_id and pro.order_id = rep.repair_order_num_alias and pro.status = 0")
                ->where("rep.repair_order_id = $order_id")
                ->select();
        $orderStatus = M()->table('zsf_order_status_history his')->field('his.order_id,his.status,his.count,his.add_time,con.content,con.content1,his.count')
                   ->join("LEFT JOIN zsf_config_status con on his.status = con.status and con.user_type = 1")
                   ->where("his.order_id = $order_id")
                   ->order('his.add_time asc')
                   ->select();
        $orderFault = M()->table('zsf_repair_order_detail det')->field('det.price,det.material_cost,det.deplete_cost,det.artificial_cost,det.fault_name,rep.mode_charging,rep.diagnosis_cost')
                    ->join("LEFT JOIN zsf_repair_order rep on rep.repair_order_id = det.repair_order_id")
                    ->where("det.repair_order_id = $order_id")
                    ->select();
        $Status = $orderData[0][status];
        $time = $orderData[0][set_time];

        foreach($orderData as $j=>$y){
            $orderData[$j]['set_time'] = date('Y-m-d H:i:s',$y['set_time']);
            if($y['book_time']!=0) {
                $orderData[$j]['book_time'] = date('Y-m-d H:i:s', $y['book_time']);
            }
            if($y['status']<=7){
                $orderData[$j]['pay'] = '未支付';
            }else{
                $orderData[$j]['pay'] = '已支付';
            }
            if($y['status'] =='1' || $y['status'] =='2' || $y['status'] =='-3'){
                $orderData[$j]['service'] = '待服务';
            }
            if($y['status'] =='-2' || $y['status'] =='3' || $y['status'] =='4'|| $y['status'] =='5'|| $y['status'] =='6' || $y['status'] =='7'){
                $orderData[$j]['service'] = '服务中';
            }
            if($y['status'] =='8' || $y['status'] =='9'){
                $orderData[$j]['service'] = '保修中';
            }
            if($y['status'] =='11' || $y['status'] =='12' || $y['status'] =='14'){
                $orderData[$j]['service'] = '退款中';
            }
            if($y['status'] =='13'){
                $orderData[$j]['service'] = '退款成功';
            }
            if($y['status'] =='-1' || $y['status'] =='10'){
                $orderData[$j]['service'] = '交易完成';
            }
        }

        //看业主暂停恢复了几次
        $times = M("OrderStatusHistory")->where("order_id = $order_id and status = 9")->select();
        if($times){
            $updateCount['count'] = 1;
            $status_id = M("OrderStatusHistory")->field('id')->where("order_id = $order_id and status = 9")->order('add_time desc')->find();
            M("OrderStatusHistory")->where("id = $status_id[id]")->save($updateCount);
        }

        foreach($orderStatus as $k=>$v){
            $orderStatus[$k]['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            if($v['count']!=0 && $v['status']!=9){
                $orderStatus[$k]['content'] = $v['content1'];
            }
            if($v['status']==11){
                $refundReason = M("RepairOrderRefund")->field('desc')->where("order_id = $v[order_id]")->find();
                $orderStatus[$k]['reason'] = $refundReason['desc'];
            }
        }

        //判断客服是否已判定
        $UserRefundExists = M('UserRefund')->where("order_id = $order_id")->find();
        if($UserRefundExists){
            $this->assign('exist',$UserRefundExists);
            $orderStatus[20]['add_time'] = date('Y-m-d H:i:s',$UserRefundExists['add_time']);
            $orderStatus[20]['content'] = "客服已处理退款，判定<br>业主退款：¥".$UserRefundExists['user_refund']."<br>师傅退款：¥".$UserRefundExists['master_refund']."<br>备注：".$UserRefundExists['remark'];
        }
        //判断客服是否已转账
        $Usertransfer = M('UserRefund')->where("order_id = $order_id and status = 2")->find();
        if($Usertransfer){
            $orderStatus[21]['add_time'] = date('Y-m-d H:i:s',$Usertransfer['refund_time']);
            $orderStatus[21]['content'] = "财务已转账，<br>业主：¥".$Usertransfer['user_refund']." 转账流水号：".$Usertransfer['user_code']."<br>师傅：¥".$Usertransfer['master_refund']." 转账流水号：".$Usertransfer['master_code']."<br>备注：".$Usertransfer['user_mark'].'-'.$Usertransfer['master_mark'];
        }

        //判断是否已退款
        if($orderData[0]['status']==13){
            $refundOrderStatus = M("order_status_history s")->field('c.name,s.*')
                               ->join("LEFT JOIN zsf_config_status c on c.status = s.status")
                               ->where("s.order_id = $order_id and s.status = 13")
                               ->select();
            $orderStatus[22]['add_time'] = date('Y-m-d H:i:s',$refundOrderStatus[0]['add_time']);
            $orderStatus[22]['content'] = $refundOrderStatus[0]['name'];
        }

        $total = 0;
        foreach($orderFault as $u=>$i){
            if($i['mode_charging']=='1'){
                $orderFault[$u]['type'] ='顺风';
            }elseif($i['mode_charging']=='2'){
                $orderFault[$u]['type'] ='标准';
            }elseif($i['mode_charging']=='3'){
                $orderFault[$u]['type'] ='专修';
            }
            $total+=$orderFault[$u]['price'];
        }
        $data[]['orderData'] = $orderData;
        $data[]['orderFault'] = $orderFault;
        $data[]['orderStatus'] = $orderStatus;

        $presentStatus = array();
        $presentStatus[0]['Service'] = '待服务';
        $presentStatus[0]['Status'] = '1';
        $presentStatus[0]['time'] = $time;

        $presentStatus[1]['Service'] = '服务中';
        if($Status=='-1'){
            $presentStatus[1]['Service'] = '已取消';
            $HistoryStatus = M('order_status_history')->field('add_time')->where("status = -1 and order_id = $order_id")->order("add_time asc")->find();
            $presentStatus[1]['Status'] = '-1';
            $presentStatus[1]['time']= $HistoryStatus['add_time'];
        }else {
            $presentStatus[2]['Service'] = '保修中';
            $presentStatus[3]['Service'] = '交易完成';
        }

        if($Status>=3){
            $HistoryStatus = M('order_status_history')->field('add_time')->where("status = 3 and order_id = $order_id")->order("add_time asc")->find();
            $presentStatus[1]['Status'] = '2';
            $presentStatus[1]['time']= $HistoryStatus['add_time'];
        }
        if($Status == 8 || $Status ==9 || $Status == 10 || $Status==11 || $Status == 12 || $Status ==13){
            $HistoryStatus = M('order_status_history')->field('add_time')->where("status = 8 and order_id = $order_id")->order("add_time asc")->find();
            $presentStatus[2]['Status'] = '3';
            $presentStatus[2]['time'] = $HistoryStatus['add_time'];
        }
        if($Status == 10 || $Status == 13){
            $HistoryStatus = M('order_status_history')->field('add_time')->where("status = $Status and order_id = $order_id")->order("add_time asc")->find();
            $presentStatus[3]['Status'] = '4';
            $presentStatus[3]['time']= $HistoryStatus['add_time'];
        }
        foreach($presentStatus as $k=>$j){
            $presentStatus[$k]['time'] = date('Y-m-d H:i:s',$j['time']);
        }
        $data[]['presentStatus'] = $presentStatus;

        $status = I('get.status');
        if($status){
            $this->assign('status',$status);
        }
        //退款金额
        if($orderData[0]['status']==11){
            $orderProtocol = M("RepairOrderProtocol")->where("protocol_id = ".$orderData[0]['protocol_id'])->find();
            if($orderProtocol['fixed_price']){
                $received_money = $orderProtocol['fixed_price'];
            }else{
                $received_money = $orderProtocol['gold'];
            }
            $refundMoney= M("RepairOrderRefund")->field('money')->where("order_id = $order_id")->find();
            $paid_money = $refundMoney['money'];

            $this->assign('received_money',$received_money);
            $this->assign('paid_money',$paid_money);
        }

        //退维保金
        if($orderData[0]['status']==9 && $orderData[0]['is_refund']==1){
            $orderProtocol = M("RepairOrderProtocol")->where("protocol_id = ".$orderData[0]['protocol_id'])->find();
            $ratio = $orderProtocol['bond_ratio']/100;

            $repair_amount = $orderData[0]['amount_paid'];
            $paid_money = bcmul($repair_amount,$ratio,3);
            $received_money = $orderProtocol['bond'];

            $this->assign('received_money',$received_money);
            $this->assign('paid_money',$paid_money);
        }


        $this->assign('detail',$data);
        $this->assign('total',$total);
        $this->display();

    }


    /**
     * 退款管理
     * @param
     */

    public function handleRefund(){
        $order_id = I('order_id');
        $name = I('name');
        $type = I('type');
        $status = I('status');
        $start_time = I('start_time');
        $end_time = I('end_time');

        if($order_id){
            $map['p.repair_order_num_alias'] =  array('like',"%$order_id%");
        }
        if($name){
            $map['a.a_uname'] = array('like',"%$name%");
        }
        if($type!=0){
            $map['e.type'] = array('eq',$type);
        }
        if($status!=0){
            $map['r.status'] = array('eq',$status);
        }
        if($start_time && $end_time) {
            $map['r.add_time'] = array('between',$start_time.','.$end_time);
        }elseif($start_time){
            $map['r.add_time'] = array('egt',$start_time);
        }

        $count= M()->table("zsf_user_refund r")
            ->field('p.repair_order_id,p.repair_order_num_alias,a.a_uname as name,e.type,r.*')
            ->join("LEFT JOIN zsf_repair_order p on r.order_id = p.repair_order_id")
            ->join("LEFT JOIN zsf_admin a on a.a_id = r.admin_id")
            ->join("LEFT JOIN zsf_repair_order_refund e on e.order_id = r.order_id")
            ->where($map)
            ->count();

        $Page  = new \Think\Page($count,self::pagecount);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show  = $Page->show();// 分页显示输出

        $data = M()->table("zsf_user_refund r")
                ->field('p.repair_order_id,p.repair_order_num_alias,a.a_uname as name,e.type,r.*')
                ->join("LEFT JOIN zsf_repair_order p on r.order_id = p.repair_order_id")
                ->join("LEFT JOIN zsf_admin a on a.a_id = r.admin_id")
                ->join("LEFT JOIN zsf_repair_order_refund e on e.order_id = r.order_id")
                ->where($map)
                ->select();

        foreach($data as $k=>$v){
            $data[$k]['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            if($v['type']==1){
                $data[$k]['type'] = '全退';
            }else{
                $data[$k]['type'] = '退维保金';
            }
            if($v['status']==1) {
                $data[$k]['status'] = '未转账';
            }else{
                $data[$k]['status'] = '已转账';
            }
        }

        $this->breadcrumb1='财务管理';
        $this->breadcrumb2='退款管理';
        $this->assign('handle',$data);
        $this->assign('page',$show);
        $this->display();
    }

    /**
     * 增加客服判定金额
     */

    public function addToRefundMoney(){
        $admin = session('user_auth');
        $order_id = I('post.order_id');
        $user_money = I('post.user_money');
        $maps['order_id'] = $order_id;
        $maps['total'] = I('post.total');
        $maps['user_refund'] = $user_money;
        $maps['master_refund'] = I('post.master_money',0);
        $maps['add_time'] = time();
        $maps['admin_id'] = $admin['uid'];
        $maps['remark'] = I('post.remark');

        //增加可申请码
        $RepairOrder = M("RepairOrder");
        $map['repair_order_id'] = array('eq',$order_id);
        $map['status'] = array('eq',9);
        $map['is_refund'] = array('eq',1);
        $updateBond = $RepairOrder->where($map)->find();

        if($updateBond){
            $save['status'] = 14;
            $RepairOrder->where($map)->save($save);

            $condition['order_type']='1';
            $condition['order_id'] = $order_id;
            $condition['add_time'] = time();
            $condition['status'] = 14;
            M('order_status_history')->add($condition);
        }

        $exist =M('UserRefund')->where("order_id = $order_id")->find();
        if($exist){
            echo 3;
            exit;
        }
        $add = M("UserRefund")->add($maps);
        if($add){
            if($user_money==0.00){
                $isApply['is_apply'] = 1;
                M("RepairOrder")->where("repair_order_id = $order_id")->save($isApply);
            }
            echo 1;
            exit;
        }else{
            echo 2;
            exit;
        }

    }

    /**
     * 获取转账信息
     */

    public function accountInfo(){
        $order_id = I('post.order_id');
        $Repair = M('RepairOrder')->where("repair_order_id = $order_id")->find();

        if($Repair['is_refund']==0){
            $data = M()->table('zsf_repair_order_refund r')
                ->field('r.channel,r.bank_name,r.account_name,r.account_num,usr.phone as user_phone,wok.phone as worker_phone,inf.id_name as worker_name,f.user_refund,f.master_refund,a.a_uname as admin_name')
                ->join("LEFT JOIN zsf_repair_order rep on rep.repair_order_id = r.order_id")
                ->join("LEFT JOIN zsf_user usr on usr.user_id = rep.user_id")
                ->join("LEFT JOIN zsf_user wok on wok.user_id = rep.worker_user_id")
                ->join("LEFT JOIN zsf_user_real_info inf on inf.user_id = rep.worker_user_id")
                ->join("LEFT JOIN zsf_user_refund f on f.order_id = r.order_id")
                ->join("LEFT JOIN zsf_admin a on a.a_id = f.admin_id")
                ->where("r.order_id = $order_id")
                ->select();
               $data[0]['check'] = "0";
        }else{
            $info = M('UserRefund')->where("order_id = $order_id")->find();
            if($info['user_refund']==0.000){
                $data = M()->table('zsf_repair_order rep')
                    ->field('usr.phone as user_phone,wok.phone as worker_phone,inf.id_name as worker_name,f.user_refund,f.master_refund,a.a_uname as admin_name')
                    ->join("LEFT JOIN zsf_user usr on usr.user_id = rep.user_id")
                    ->join("LEFT JOIN zsf_user wok on wok.user_id = rep.worker_user_id")
                    ->join("LEFT JOIN zsf_user_real_info inf on inf.user_id = rep.worker_user_id")
                    ->join("LEFT JOIN zsf_user_refund f on f.order_id = rep.repair_order_id")
                    ->join("LEFT JOIN zsf_admin a on a.a_id = f.admin_id")
                    ->where("rep.repair_order_id = $order_id")
                    ->select();
                $data[0]['check'] = "1";
            }else{
                $data = M()->table('zsf_repair_order_refund r')
                    ->field('r.channel,r.bank_name,r.account_name,r.account_num,usr.phone as user_phone,wok.phone as worker_phone,inf.id_name as worker_name,f.user_refund,f.master_refund,a.a_uname as admin_name')
                    ->join("LEFT JOIN zsf_repair_order rep on rep.repair_order_id = r.order_id")
                    ->join("LEFT JOIN zsf_user usr on usr.user_id = rep.user_id")
                    ->join("LEFT JOIN zsf_user wok on wok.user_id = rep.worker_user_id")
                    ->join("LEFT JOIN zsf_user_real_info inf on inf.user_id = rep.worker_user_id")
                    ->join("LEFT JOIN zsf_user_refund f on f.order_id = r.order_id")
                    ->join("LEFT JOIN zsf_admin a on a.a_id = f.admin_id")
                    ->where("r.order_id = $order_id")
                    ->select();
                $data[0]['check'] = "2";
            }
        }
        $this->ajaxReturn($data);
    }

    /**
     * 转账
     * @param 流水号
     * @param 备注
     */

    public function refundSuc(){
        $order_id = I('post.order_id');
        $flow_num = I('post.flow_num');
        $user_remark = I('post.user_remark','');
        $master_remark = I('post.master_remark','');
        $map['order_id'] = array('eq',$order_id);
        $refund = M('UserRefund')->where($map)->find();

        if($refund){
            $maps['user_code'] = $flow_num;
            $maps['user_mark'] = $user_remark;
            $maps['master_mark'] = $master_remark;

            $Repair = M("RepairOrder")->where("repair_order_id = $order_id")->find();
            $Protocol = M("RepairOrderProtocol")->where("protocol_id = $Repair[protocol_id]")->find();
            $relation = M("RepairOrderRefund r")->field('r.type,z.user_refund,z.master_refund')
                        ->join("LEFT JOIN zsf_user_refund z on r.order_id = z.order_id")
                        ->where("r.order_id = $order_id")
                        ->select();

            $maintain = $Protocol['maintain'];
            $bond = $Protocol['bond'];
            $worker_user_id = $Repair['worker_user_id'];

            if($relation[0]['type']=='1') {
                //从师傅钱包扣除 维修金
                $delWorkerMaintainMoney = M("UserMoney")->where("user_id = $worker_user_id")->setDec('repair_money', $maintain);
                $this->addToMoneyHistory($worker_user_id, 4, $Repair['repair_order_id'], $Repair['protocol_id'], $maintain, 0, NULL, 1, "订单" . $Repair['repair_order_num_alias'] . "发生退款，资金转入平台");
                //从师傅钱包扣除 维保金
                $delWorkerBondMoney = M("UserMoney")->where("user_id = $worker_user_id")->setDec('repair_bond', $bond);
                $this->addToMoneyHistory($worker_user_id, 4, $Repair['repair_order_id'], $Repair['protocol_id'], $bond, 0, NULL, 2, "订单" . $Repair['repair_order_num_alias'] . "发生退款，资金转入平台");

                if($refund['master_refund']!=0.00){
                    $addWorkerbalanceMoney = M("UserMoney")->where("user_id = $worker_user_id")->setInc('balance',$refund['master_refund']);
                    $num = $this->addToMoneyHistory($worker_user_id,4,$Repair['repair_order_id'],$Repair['protocol_id'],$refund['master_refund'],1,NULL,5,"订单".$Repair['repair_order_num_alias']."发生退款，资金转入师傅余额");
                    if($addWorkerbalanceMoney && $num){
                        $maps['master_code'] = $num;
                    }
                }
                $maps['status'] = 2;
                $maps['refund_time'] =time();

                $repair['repair_order_id'] = $order_id;
                $repair['status'] = 13;
                M('repair_order')->save($repair);

                $condition['order_type']='1';
                $condition['order_id'] = $order_id;
                $condition['add_time'] = time();
                $condition['status'] = 13;
                M('order_status_history')->add($condition);

                $succ = M("UserRefund")->where("order_id = $order_id")->save($maps);
                if($succ){
                    echo 1;
                    exit;
                }else{
                    echo 2;
                    exit;
                }
            }else{
                //锁定期后 从师父钱包扣除 维保金
                //从师傅钱包扣除 维保金
                $delWorkerBondMoney = M("UserMoney")->where("user_id = $worker_user_id")->setDec('repair_bond', $bond);
                $this->addToMoneyHistory($worker_user_id, 4, $Repair['repair_order_id'], $Repair['protocol_id'], $bond, 0, NULL, 2, "订单" . $Repair['repair_order_num_alias'] . "发生退款，资金转入平台");

                if($refund['master_refund']!=0.00){
                    $addWorkerbalanceMoney = M("UserMoney")->where("user_id = $worker_user_id")->setInc('balance',$refund['master_refund']);
                    $num = $this->addToMoneyHistory($worker_user_id,4,$Repair['repair_order_id'],$Repair['protocol_id'],$refund['master_refund'],1,NULL,5,"订单".$Repair['repair_order_num_alias']."发生退款，资金转入师傅余额");
                    if($addWorkerbalanceMoney && $num){
                        $maps['master_code'] = $num;
                    }
                }
                $maps['status'] = 2;
                $maps['refund_time'] =time();

                $repair['repair_order_id'] = $order_id;
                $repair['status'] = 13;
                M('repair_order')->save($repair);

                $condition['order_type']='1';
                $condition['order_id'] = $order_id;
                $condition['add_time'] = time();
                $condition['status'] = 13;
                M('order_status_history')->add($condition);

                $succ = M("UserRefund")->where("order_id = $order_id")->save($maps);
                if($succ){
                    echo 1;
                    exit;
                }else{
                    echo 2;
                    exit;
                }

            }
        }else{
            echo 3;
            exit;
        }



    }


    /**
     * 资金流水
     * @remark 维修金、维保金、小费
     */

    private function addToMoneyHistory($user_id,$type,$order_id,$protocol_id,$total,$is_plus,$balance,$flag,$remark){
        $UserMoneyHistory = M('MoneyHistory');
        $addMaps['user_id'] = $user_id;
        $addMaps['type'] = $type;
        $addMaps['order_id'] = $order_id;
        $addMaps['protocol_id'] = $protocol_id;
        $addMaps['total'] = $total;
        $addMaps['is_plus'] = $is_plus;
        $addMaps['balance'] = $balance;
        $addMaps['add_time'] = time();
        $addMaps['flag'] = $flag;
        $addMaps['remark'] = $remark;
        $result = $UserMoneyHistory->add($addMaps);

        return $result;
    }



//    /**
//     * 客服介入
//     * @param order_id 订单id
//     */
//    public function Customer_Services(){
//        $this->breadcrumb1='维修订单';
//        $this->breadcrumb2='订单详情';
//        $this->breadcrumb3='客服介入';
//
//        $order_id = I('get.order_id');
//        $Maps['order_id'] = $order_id;
//        $feedback = M('repair_order_service')->where($Maps)->select();
//        foreach($feedback as $k=>$v){
//            $feedback[$k]['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
//            for($i=1;$i<=7;$i++){
//                if(empty($v["certificate$i"])){
//                    unset($feedback[$k]["certificate$i"]);
//                }else{
//                    $feedback[$k]["certificate$i"] = $v["certificate$i"].'?imageView2/1/w/200/h/150';
//                }
//            }
//        }
//        $this->url2=U("Order/normal/order_id/$order_id");
//        $this->assign('feedback',$feedback);
//        $this->display('general');
//
//    }

//    /**
//     * 客服评论
//     * @param order_id
//     * @param description
//     */
//    public function service_comment(){
//        $description = trim(I('post.description'));
//        $order_id = I('post.order_id');
//        $maps['order_id'] = $order_id;
//        $maps['user_type'] = 3;
//        $maps['content'] = $description;
//        $maps['add_time'] = time();
//        $data = M('repair_order_service')->add($maps);
//        if($data){
//            echo 1;
//            exit;
//        }else{
//            echo 2;
//            exit;
//        }
//    }

//    /**
//     * 客服拒绝退款
//     * @param order_id
//     */
//
//    public function refundRefuse(){
//        $order_id = I('post.order_id');
//        $repairStatus = M('repair_order')->field('status')->where("repair_order_id = $order_id")->find();
//        if($repairStatus['status']!=14){
//            echo 3;
//            exit;
//        }
//        //更新退款记录表
//        $feedback = I('post.content');
//        $maps['order_id'] = $order_id;
//        $sets['feedback'] = $feedback;
//        $sets['status'] = 2;
//        $repairRefund = M('repair_order_refund')->where($maps)->save($sets);
//
//        //增加历史状态
//        $condition['order_type']='1';
//        $condition['order_id'] = $order_id;
//        $condition['add_time'] = time();
//        $condition['status'] = 16;
//        $addHistory = M('order_status_history')->add($condition);
//        $status = 8;
//
//        $repair['repair_order_id'] = $order_id;
//        $repair['status'] = $status;
//        $repairSave = M('repair_order')->save($repair);
//
//        $condition['order_type']='1';
//        $condition['order_id'] = $order_id;
//        $condition['add_time'] = time();
//        $condition['status'] = $status;
//        $end = M('order_status_history')->add($condition);
//
//        if($repairRefund && $addHistory && $repairSave && $end){
//            echo 1;
//            exit;
//        }else{
//            echo 2;
//            exit;
//        }
//
//    }

}